$("#test-limit-one").blur(function(){
});
$("#test-limit-two").blur(function (){
    // console.log("hello");
})
/*=================================默认时间显示===========================*/

var defaultGetCarDate = new Date();
var defaultReturnCarDate = new Date();
// defaultGetCarDate.setHours(13)
defaultGetCarDate.setMinutes(0);
defaultReturnCarDate.setMinutes(0);
defaultReturnCarDate.setDate(defaultReturnCarDate.getDate()+1);


var defaultGetCarDateHours = defaultGetCarDate.getHours();

if(defaultGetCarDateHours >= 0 && defaultGetCarDateHours < 12){
    defaultGetCarDate.setHours(12);
    defaultReturnCarDate.setHours(12);
}else if(defaultGetCarDateHours >= 12 && defaultGetCarDateHours <15){
    defaultGetCarDate.setHours(15);
    defaultReturnCarDate.setHours(15);
}else if(defaultGetCarDateHours >= 15 && defaultGetCarDateHours<18) {
    defaultGetCarDate.setHours(18);
    defaultReturnCarDate.setHours(18);
}else{
    defaultGetCarDate.setHours(8);
    defaultGetCarDate.setDate(defaultGetCarDate.getDate() + 1);
    defaultReturnCarDate.setHours(8);
    defaultReturnCarDate.setDate(defaultReturnCarDate.getDate() + 1);
}

// 取车 年月日
$("#test-limit-one").attr("value",formatDate(defaultGetCarDate));
// 取车 时分
$("#test-limit-three").attr("value",formatTime(defaultGetCarDate));
// 还车 年月日
$("#test-limit-two").attr("value",formatDate(defaultReturnCarDate));
// 还车 时分
$("#test-limit-four").attr("value",formatTime(defaultReturnCarDate));

/*==========================多条件动态查询===========================*/
/*A表示 '<a></a>' 标签*/
var chooseModelA = document.getElementById('choose-model').getElementsByTagName('a');
var chooseBrandA = document.getElementById('brandlist').getElementsByTagName('a');
var choosePriceA = document.getElementById('pricelist').getElementsByTagName('a');
var chooseGrarA = document.getElementById('grarlist').getElementsByTagName('a');
var chooseSeatA = document.getElementById('seatlist').getElementsByTagName('a');
var fieldOrderByA = document.getElementById('field-orderby').getElementsByTagName('a');

var oChooseModel = document.getElementById("choose-model");
var oChooseBrand = document.getElementById("brandlist");
var oChoosePrice = document.getElementById("pricelist");
var oChooseGrar = document.getElementById("grarlist");
var oChooseSeat = document.getElementById("seatlist");
var oFieldOrderBy = document.getElementById("field-orderby");

// chooseModelA[0].className = 'active';
// chooseBrandA[0].className = 'active';
// choosePriceA[0].className = 'active';
// chooseGrarA[0].className = 'active';
// chooseSeatA[0].className = 'active';
// fieldOrderByA[0].className = 'active';




for(var i = 0; i < chooseModelA.length;i++){
    chooseModelA[i].onclick = function(){
        var siblings = this.parentElement.children;
        for(var j=0;j<siblings.length;j++){
            siblings[j].className = '';
        }
        this.className = 'choose-model-active';
        if(this.parentNode == oChooseModel){
            getResult();
        }
    }
}

for(var i = 0; i < chooseBrandA.length;i++){
    chooseBrandA[i].onclick = function(){
        var siblings = this.parentElement.children;
        for(var j=0;j<siblings.length;j++){
            siblings[j].className = '';
        }
        this.className = 'active';
        if(  this.parentNode == oChooseBrand   ){
            getResult();
        }
    }
}

for(var i = 0; i < choosePriceA.length;i++){
    choosePriceA[i].onclick = function(){
        var siblings = this.parentElement.children;
        for(var j=0;j<siblings.length;j++){
            siblings[j].className = '';
        }
        this.className = 'active';
        if(this.parentNode == oChoosePrice ){
            getResult();
        }
    }
}

for(var i = 0; i < chooseGrarA.length;i++){
    chooseGrarA[i].onclick = function(){
        var siblings = this.parentElement.children;
        for(var j=0;j<siblings.length;j++){
            siblings[j].className = '';
        }
        this.className = 'active';
        if(this.parentNode == oChooseGrar  ){
            getResult();
        }
    }
}

for(var i = 0; i < chooseSeatA.length;i++){
    chooseSeatA[i].onclick = function(){
        var siblings = this.parentElement.children;
        for(var j=0;j<siblings.length;j++){
            siblings[j].className = '';
        }
        this.className = 'active';
        if(this.parentNode ==  oChooseSeat  ){
            getResult();
        }
    }
}


for(var i = 0; i < fieldOrderByA.length;i++){
    fieldOrderByA[i].onclick = function(){
        var siblings = this.parentElement.parentElement.children;
        for(var j=0;j<siblings.length;j++){
            siblings[j].firstElementChild.className = '';
        }
        this.className = 'field-orderby-active';
        if(
            this.parentNode.parentNode == oFieldOrderBy ){
            getResult();
        }
    }
}
$(".submit-btn").click(function (){
    getResult();
})

function getResult(){
    var o1 = 0, o2 = 0, o3 =0 , o4 = 0, o5 = 0;
    for(var i=0; i<chooseModelA.length; i++){
        if(chooseModelA[i].className == 'choose-model-active'){
            o1 = i;
        }
    }
    for(var i=0; i<chooseBrandA.length; i++){
        if(chooseBrandA[i].className == 'active'){
            o2 = i;
        }
    }
    for(var i=0; i<choosePriceA.length; i++){
        if(choosePriceA[i].className == 'active'){
            o3 = i;
        }
    }
    for(var i=0; i<chooseSeatA.length; i++){
        if(chooseSeatA[i].className == 'active'){
            o4 = i;
        }
    }
    for(var i=0; i<fieldOrderByA.length; i++){
        if(fieldOrderByA[i].className == 'field-orderby-active'){
            o5 = i;
        }
    }


    var borrowStoreId = $("#borrow-store-id").text();
    var returnStoreId = $("#return-store-id").text();

    var getCarDate = $("#test-limit-one").val();
    var getCarTime = $("#test-limit-three").val();
    var returnCarDate = $("#test-limit-two").val();
    var returnCarTime = $("#test-limit-four").val();
    getCarTime = getCarDate+" " + getCarTime;

    returnCarTime = returnCarDate + " " +returnCarTime;
    var returnCarTime2 = new Date(returnCarTime);

    returnCarTime2 = returnCarTime2.setHours(returnCarTime2.getHours()-9);
    getCarTime = new Date(getCarTime);
    if(new Date(getCarTime) <= new Date()){
        alert("取车时间不能小于当前时间~");
    }else if(new Date(getCarTime) >= returnCarTime2){
        alert("取车时间与还车时间间隔不能小于九个小时~");
    }

    var carType = chooseModelA[o1].firstElementChild.firstElementChild.textContent;
    var carBrand = chooseBrandA[o2].text;
    var carDailyPrice = choosePriceA[o3].text;
    var carSeatNumber = chooseSeatA[o4].text;
    var orderBy = fieldOrderByA[o5].text;
    // var pageNum = chooseBrandA[o2].text;


    /*showCarList(carType, carBrand,
        carDailyPrice,
        carSeatNumber,
        orderBy,1)*/
    showCarListByContainAndStore(
        borrowStoreId,
        getCarTime,
        carType,
        carBrand,
        carDailyPrice,
        carSeatNumber,orderBy,1)
}



/*===================时间=====================*/
layui.use('laydate', function(){
    var laydate = layui.laydate;

    //常规用法
    laydate.render({
        elem: '#test1'
    });

    //国际版
    laydate.render({
        elem: '#test1-1'
        ,lang: 'en'
    });

    //年选择器
    laydate.render({
        elem: '#test2'
        ,type: 'year'
    });

    //年月选择器
    laydate.render({
        elem: '#test3'
        ,type: 'month'
    });

    //时间选择器
    laydate.render({
        elem: '#test4'
        ,type: 'time'
    });

    //日期时间选择器
    laydate.render({
        elem: '#test5'
        ,type: 'datetime'
    });

    //日期范围
    laydate.render({
        elem: '#test6'
        //设置开始日期、日期日期的 input 选择器
        //数组格式为 2.6.6 开始新增，之前版本直接配置 true 或任意分割字符即可
        ,range: ['#test-startDate-1', '#test-endDate-1']
    });

    //年范围
    laydate.render({
        elem: '#test7'
        ,type: 'year'
        ,range: true
    });

    //年月范围
    laydate.render({
        elem: '#test8'
        ,type: 'month'
        ,range: true
    });

    //时间范围
    laydate.render({
        elem: '#test9'
        ,type: 'time'
        ,range: true
    });

    //日期时间范围
    laydate.render({
        elem: '#test10'
        ,type: 'datetime'
        ,range: true
    });

    //自定义格式
    laydate.render({
        elem: '#test11'
        ,format: 'yyyy年MM月dd日'
    });
    laydate.render({
        elem: '#test12'
        ,format: 'dd/MM/yyyy'
    });
    laydate.render({
        elem: '#test13'
        ,format: 'yyyyMMdd'
    });
    laydate.render({
        elem: '#test14'
        ,type: 'time'
        ,format: 'H点m分'
    });
    laydate.render({
        elem: '#test15'
        ,type: 'month'
        ,range: '~'
        ,format: 'yyyy-MM'
    });
    laydate.render({
        elem: '#test16'
        ,type: 'datetime'
        ,range: '到'
        ,format: 'yyyy年M月d日H时m分s秒'
    });

    //开启公历节日
    laydate.render({
        elem: '#test17'
        ,calendar: true
    });

    //自定义重要日
    laydate.render({
        elem: '#test18'
        ,mark: {
            '0-10-14': '生日'
            ,'0-12-31': '跨年' //每年的日期
            ,'0-0-10': '工资' //每月某天
            ,'0-0-15': '月中'
            ,'2017-8-15': '' //如果为空字符，则默认显示数字+徽章
            ,'2099-10-14': '呵呵'
        }
        ,done: function(value, date){
            if(date.year === 2017 && date.month === 8 && date.date === 15){ //点击2017年8月15日，弹出提示语
                layer.msg('这一天是：中国人民抗日战争胜利72周年');
            }
        }
    });

    var minDate = new Date();
    var maxDate = new Date();
    maxDate = maxDate.setDate(maxDate.getDate()+60);
    maxDate = new Date(maxDate)

    //限定可选日期
    var ins22 = laydate.render({
        elem: '#test-limit-one'
        ,min: formatDate(minDate)
        ,max: formatDate(maxDate)
    });
    /*================注意还车时间必须大于租车时间（未实现）==============*/
    var minDate2 = new Date();
    var maxDate2 = new Date();
    minDate2 = minDate2.setDate(minDate2.getDate()+1);
    maxDate2 = maxDate2.setDate(maxDate.getDate()+60);
    minDate2 = new Date(minDate2);
    maxDate2 = new Date(maxDate2);
    // $(".car-time").attr("placeholder","20:30:22");

    var ins22 = laydate.render({
        elem: '#test-limit-two'
        ,min: formatDate(minDate2)
        ,max: formatDate(maxDate2)
    });
    /*定位*/

    //前后若干天可选，这里以7天为例
    laydate.render({
        elem: '#test-limit2'
        ,min: -7
        ,max: 7
    });

    //限定可选时间
    laydate.render({
        elem: '#test-limit-three'
        ,type: 'time'
        ,min: '8:00:00'
        ,max: '18:00:00'
        ,format: 'H:m'
        ,btns: ['clear', 'confirm']
    });
    laydate.render({
        elem: '#test-limit-four'
        ,type: 'time'
        ,format: 'H:m'
        ,min: '8:00:00'
        ,max: '18:00:00'
        ,btns: ['clear', 'confirm']
    });


    //同时绑定多个
    lay('.test-item').each(function(){
        laydate.render({
            elem: this
            ,trigger: 'click'
        });
    });

    //初始赋值
    laydate.render({
        elem: '#test19'
        ,value: '1989-10-14'
        ,isInitValue: true
    });

    //选中后的回调
    laydate.render({
        elem: '#test20'
        ,done: function(value, date){
            layer.alert('你选择的日期是：' + value + '<br>获得的对象是' + JSON.stringify(date));
        }
    });

    //日期切换的回调
    laydate.render({
        elem: '#test21'
        ,change: function(value, date){
            layer.msg('你选择的日期是：' + value + '<br><br>获得的对象是' + JSON.stringify(date));
        }
    });
    //不出现底部栏
    laydate.render({
        elem: '#test22'
        ,showBottom: false
    });

    //只出现确定按钮
    laydate.render({
        elem: '#test23'
        ,btns: ['confirm']
    });

    //自定义事件
    laydate.render({
        elem: '#test24'
        ,trigger: 'mousedown'
    });

    //点我触发
    laydate.render({
        elem: '#test25'
        ,eventElem: '#test25-1'
        ,trigger: 'click'
    });

    //双击我触发
    lay('#test26-1').on('dblclick', function(){
        laydate.render({
            elem: '#test26'
            ,show: true
            ,closeStop: '#test26-1'
        });
    });

    //日期只读
    laydate.render({
        elem: '#test27'
        ,trigger: 'click'
    });

    //非input元素
    laydate.render({
        elem: '#test28'
    });

    //墨绿主题
    laydate.render({
        elem: '#test29'
        ,theme: 'molv'
    });

    //自定义颜色
    laydate.render({
        elem: '#test30'
        ,theme: '#393D49'
    });

    //格子主题
    laydate.render({
        elem: '#test31'
        ,theme: 'grid'
    });


    //直接嵌套显示
    laydate.render({
        elem: '#test-n1'
        ,position: 'static'
    });
    laydate.render({
        elem: '#test-n2'
        ,position: 'static'
        ,lang: 'en'
    });
    laydate.render({
        elem: '#test-n3'
        ,type: 'month'
        ,position: 'static'
    });
    laydate.render({
        elem: '#test-n4'
        ,type: 'time'
        ,position: 'static'
    });
});

// 格式化时间
function formatDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    var d = date.getDate();
    return (y + '-' + m + '-' + d);
};


function formatTime(time){
    return time.getHours() + ':' + time.getMinutes();
}
function formatTimeU(time){
    return time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds();
}

/*===========Ajax car数据渲染=================*/

var globalCarType;
var globalCarBrand;
var globalCarDailyPrice;
var globalCarSeatNumber;
var globalOrderBy;
var globalPageNum;

// 根据多条件进行分页查询
function showCarList(carType, carBrand,
                     carDailyPrice, carSeatNumber,
                     orderBy,pageNum) {
    globalCarType = carType;
    globalCarBrand = carBrand;
    globalCarDailyPrice = carDailyPrice;
    globalCarSeatNumber = carSeatNumber;
    globalOrderBy = orderBy;
    globalPageNum = pageNum;

    var minCarDailyPrice;
    var maxCarDailyPrice;
    if(carType == "全部")
        carType = "-1";
    if(carBrand == "全部")
        carBrand = "-1"
    if(carDailyPrice == "全部") {
        minCarDailyPrice = -1;
        maxCarDailyPrice = -1;
    }
    else if(carDailyPrice == "100元以下") {
        minCarDailyPrice = -1;
        maxCarDailyPrice = 100;
    }
    else if(carDailyPrice == "100-200元"){
        minCarDailyPrice = 100;
        maxCarDailyPrice = 200;
    }else if(carDailyPrice = "200-300元"){
        minCarDailyPrice = 200;
        maxCarDailyPrice = 300;
    }else if(carDailyPrice = "300元以上"){
        minCarDailyPrice = 300;
        maxCarDailyPrice = -1;
    }
    if(carSeatNumber == "全部")
        carSeatNumber = -1
    else if(carSeatNumber == "2座")
        carSeatNumber = 2;
    else if(carSeatNumber == "4座")
        carSeatNumber = 4;
    else if(carSeatNumber == "5座")
        carSeatNumber = 5;
    else if(carSeatNumber == "7座")
        carSeatNumber = 7;
    if(orderBy == "默认排序")
        orderBy = "-1"
    else if(orderBy == "按租金降序")
        orderBy = "car_daily_price desc"
    else if(orderBy == "按租金升序")
        orderBy = "car_daily_price asc"
    if(orderBy == "按排量降序")
        orderBy = "car_displacement desc"
    else if(orderBy == "按排量升序")
        orderBy = "car_displacement asc"
    if(typeof(pageNum) != "number")
        pageNum = 1;
    var url = '${pageContext.request.contextPath}/car/' + carType + '/'
        + carBrand + '/' + minCarDailyPrice + '/' + maxCarDailyPrice + '/'
        + carSeatNumber + '/' + orderBy + '/' + pageNum + '';
    $.get(url, null,
        function (result){
        $(".det-carlist ul").html("");
            // console.log(JSON.stringify(result));
            if(result.code == 200) {
                var carArray = result.data.list;
                for (var i = 0; i < carArray.length; i++) {
                    var carId = carArray[i].carId;
                    var carName = carArray[i].carName;
                    var carDailyPrice = carArray[i].carDailyPrice;
                    var carImagePath = carArray[i].carImagePath;
                    var carDisplacement = carArray[i].carDisplacement; // 排量
                }

                var liEle = '<li class="licar-picbox">\n' +
                    '                <div class="licar-picinfo">\n' +
                    '                    <img src="'+ carImagePath+ '">\n' +
                    '                </div>\n' +
                    '                <div class="licar-namebox">\n' +
                    '                    <p class="car-nameinfo"><span>'+carName+'</span></p>\n' +
                    '                    <p class="car-introinfo">\n' +
                    // '                        <span>|</span>\n' +
                    '                        <span>'+carDisplacement+'</span>\n' +
                    '                        <a href="${pageContext.request.contextPath}/car/detail/' + carId + '" class="show-car-detail">车辆详情</a>\n' +
                    '                    </p>\n' +
                    '                </div>\n' +
                    '                <div class="licar-info">\n' +
                    '                    <p class="condition1">\n' +
                    '                            <span class="carprice">\n' +
                    '                                <i class="symbol">￥</i>\n' +
                    '                                <em class="total-price">'+carDailyPrice+'</em>/日均\n' +
                    '                            </span>\n' +
                    '                        <span class="licar-btn">\n' +
                    '                                <a href="">预订</a>\n' +
                    '                            </span>\n' +
                    '                    </p>\n' +
                    '                </div>\n' +
                    '            </li>';
                $(".det-carlist ul").append(liEle);
            }

            // 根据店铺和时间以及多条件查询
            // 初始化显示全部的门店
            $("#borrow-store").click(function (){
                $("#borrow-store").val("");
            })
            $("#return-store").click(function (){
                $("#return-store").val("");
            })
            var storeArr;
            initializationStore();
            function initializationStore() {
                $("#borrow-store").val("");
                var borrowStoreList = $("#borrow-store-list").html();
                if(borrowStoreList == "") {
                    var storeCity = $("#J-city-get").val();
                    var url = "${pageContext.request.contextPath}/store/" + storeCity;
                    $.get(url, null,
                        function (result) {
                            storeArr = result.data;
                            for (var i = 0; i < storeArr.length; i++) {
                                var optionEle = '<option>' + storeArr[i].storeName + '</option>\n';
                                $("#borrow-store-list").append(optionEle);
                                $("#return-store-list").append(optionEle);
                            }

                            $("#borrow-store").val(storeArr[0].storeName);
                            $("#return-store").val(storeArr[0].storeName);
                            $("#borrow-store-id").text(storeArr[0].storeId);
                            $("#return-store-id").text(storeArr[0].storeId);

                            var getCarDate = $("#test-limit-one").val();
                            var getCarTime = $("#test-limit-three").val();

                            getCarTime = getCarDate + " " + getCarTime;
                            getCarTime = new Date(getCarTime);

                            showCarListByContainAndStore(
                                storeArr[0].storeId,
                                getCarTime,
                                "全部",
                                "全部",
                                "全部",
                                "全部",
                                "默认排序",
                                1
                            )


                        });
                }
            }
            $("#borrow-store").blur(function (){
                setSpanBorrowStoreId(storeArr);
            });
            $("#return-store").blur(function (){
                setSpanReturnStoreId(storeArr)
            });
            function setSpanBorrowStoreId(storeArr){
                var borrowStoreName = $("#borrow-store").val();

                if(borrowStoreName != ""){
                    for(var j = 0; j <storeArr.length;j++){
                        var storeName = storeArr[j].storeName;
                        var storeId = storeArr[j].storeId;
                        if(borrowStoreName == storeName) {
                            $("#borrow-store-id").text(storeId);
                            var getStoreUrl = "${pageContext.request.contextPath}/get_store/by_id";
                            $.get(getStoreUrl,{
                                storeId:storeId
                            },function (result){
                                $("#right-store").html("");
                                console.log(JSON.stringify(result));
                                var storeName = result.data.storeName;
                                var storeTel = result.data.storeTel;
                                var storeBusinessTime = result.data.storeBusinessTime;
                                var storeProvince =  result.data.storeProvince;
                                var storeCity = result.data.storeCity;
                                var storeArea = result.data.storeArea;
                                var storeDetailAddress = result.data.storeDetailAddress;
                                storeDetailAddress = storeProvince + "省" + storeCity + "市" + storeArea + storeDetailAddress;
                                var liEle = '   <li>取车门店：</li>\n' +
                                    '            <li>\n' +
                                    '                <h4>' + storeName + '</h4>\n' +
                                    '            </li>\n' +
                                    '            <li>\n' +
                                    '                <span>' + storeDetailAddress + '</span>\n' +
                                    '            </li>\n' +
                                    '            <li>\n' +
                                    '                <strong>门店电话：<span>' + storeTel + '</span></strong>\n' +
                                    '            </li>\n' +
                                    '            <li>\n' +
                                    '                <strong>营业时间：<span>' + storeBusinessTime + '</span></strong>\n' +
                                    '            </li>';
                                $("#right-store").append(liEle);
                            })
                            break;
                        }else if(j == storeArr.length - 1){
                            alert("门店名输入有误~重新选择下吧~")
                            $("#borrow-store").val(storeArr[0].storeName)
                        }
                        // else if()
                    }
                }else{
                    alert("请选择门店~");
                    $("#borrow-store").val(storeArr[0].storeName)
                }
            }
            function setSpanReturnStoreId(storeArr){
                // console.log("hello");
                var returnStoreName = $("#return-store").val();
                // console.log("returnStoreName != 空："+ (returnStoreName != ""));
                // console.log("returnStoreName" + returnStoreName);

                if(returnStoreName != ""){
                    for(var j = 0; j <storeArr.length;j++){
                        var storeName = storeArr[j].storeName;
                        var storeId = storeArr[j].storeId;
                        if(returnStoreName == storeName) {
                            $("#return-store-id").text(storeId);
                            break;
                        }else if(j == storeArr.length - 1){
                            alert("门店名输入有误,重新选择下吧")
                            $("#return-store").val(storeArr[0].storeName)
                        }
                        // else if()
                    }
                }else{
                    alert("请选择门店");
                    $("#return-store").val(storeArr[0].storeName)
                }
            }
        });

}